package com.gemantic.task.handler;


import java.util.Date;

import com.gemantic.task.dto.ResResult;
import com.gemantic.task.dto.TaskContext;
import com.gemantic.task.exception.NetworkException;
import com.gemantic.task.util.ExceptionUtil;
import com.gemantic.task.util.TaskUtil;

/**
 * @author xiedi
 * @date 2022/09/16
 **/
public abstract class BaseTaskHandler<T> implements ITaskHandler<T> {
    public static final int ESTIMATE_RUN_MINUTE_SHORT = 2;
    protected static final int ESTIMATE_RUN_MINUTE_LONG = 30;
    private static final int NOTICE_RETRY_TIMES = 5;


    @Override
    public String getHandlerName(TaskContext context) {
        return this.getClass().getSimpleName();
    }

    @Override
    public ResResult handleException(TaskContext taskContext, Exception ex) {
        if (ex instanceof NetworkException) {
            if (taskContext.getRetryTimes() > 0
                    && taskContext.getRetryTimes() % NOTICE_RETRY_TIMES == 0) {
                return ResResult.retryNotice(String.format("任务已经执行%s次，%s",
                        taskContext.getRetryTimes(),
                        ExceptionUtil.getMessage(ex)), null);
            } else {
                return ResResult.retry(ExceptionUtil.getMessage(ex), null);
            }
        }
        return ResResult.fromException(ex);
    }

    @Override
    public Date getNextRunTime(TaskContext context, ResResult result) {
        return TaskUtil.getNextRunTime(context, result);
    }

    @Override
    public ResResult beforeProcess(T processData, TaskContext context) {
        return null;
    }

    @Override
    public ResResult afterProcess(TaskContext context) {
        return null;
    }

    @Override
    public ResResult needPostpone(T data, TaskContext context) {
        return null;
    }

    @Override
    public int estimateRunMinutes() {
        return ESTIMATE_RUN_MINUTE_SHORT;
    }

    @Override
    public ResResult afterMaxRetryTimes(T data, TaskContext context) {
        //客户端自定义实现
        return null;
    }

    @Override
    public ResResult afterMaxRunTime(T data, TaskContext context) {
        //客户端自定义实现
        return null;
    }

    @Override
    public int getMaxRunTime(T data) {
        return TaskUtil.getMaxDateSeconds();
    }

}
